<?php
namespace app\wxapp\controller;

use app\model\Record; 
use app\model\Theme; 
use app\model\Bargain; 
use app\model\Worker; 
use app\model\Fans; 
use app\model\Order; 
use app\model\Relation; 

class BargainPay extends Base
{
    public function Bargain_pay()
    { 

global $_G, $_P;
$fans = $this->checkuser();
// $system=$_G['system'];
$system=$_G['system'];
$themeid = intval($_P['themeid']);
$theme = Theme::getThemeByIdxcx($themeid);
if(empty($theme['id'])){
    wxapp_result(1, '活动入口不正确');
    exit;
}
$config =   Theme::getConfig($themeid);
$config = Bargain::format_bargain_config($config,$_P['products_id']);



$recordid   = intval($_P['recordid']);
$joinid   = intval($_P['joinid']);
if ($joinid==20){
    $recordid = 0;
}
// URL参数

// 20发起砍价
// 21随时下单
// 22底价下单
// 23原价购买-单买
// 24抢定套餐

// 10补余款
// 999邀请好友
// 11我的定单
// 12核销定单
// 15保存多选
$renshu=0;
if ($joinid==21 || $joinid==22) {
    $yukuan = 1;
}
if ($joinid==10){
    $joinid=8;
    $yukuan=1;
}elseif ($joinid==4) {
    $joinid = 4;
    $renshu = 1;
}elseif ($joinid==5) {
    $joinid = 5;
    $renshu = 2;
}elseif ($joinid==115) {
    $joinid = 115;
    //保存多选
}


//无时间限制 存在未过期砍价实例,
if (!$config['bargain_limittime'] && $joinid == 20){
    if (empty($config['bargain_products'])){
        $has_entry = Bargain::getUserCanUsedBargainEntry($themeid,$_G['member']['uid']);
        if ($has_entry && $has_entry['status']!=3 ){
            wxapp_result(1, '您有砍价进行中，不可发起新的砍价！');
        }
    }elseif (!empty($_P['products_id'])){
//如果当前商品存在砍价，则只能发一起个砍价
        $process_sql = " select * from ".tablename(t_bargain_entry)." where uid='{$_G['member']['uid']}' and status =2 and themeid=$themeid order by created_at desc limit 1";
        $process_item =  db_find($process_sql);
        if ($process_item ){
            wxapp_result(1, '您有砍价进行中，不可发起新的砍价！');
        }
        $process_sql = " select * from ".tablename(t_bargain_entry)." where uid='{$_G['member']['uid']}' and status < 3 and products_id='{$_P['products_id']}' and themeid=$themeid order by created_at desc limit 1";
        $process_item =  db_find($process_sql);
        if ($process_item ){
            wxapp_result(1, '此产品您只能发起一次砍价');
        }
    }
}


//未支付的进行较验是否已支付
Order::checkorder($themeid,$config,$system);


// $type      = $_P['type'];
// $forward   = $_P['forward'];
$pm = array(":uniacid"=>$_G['mpid'],":themeid"=>$themeid);
$p = array(":openid"=>$_G['openid'],":themeid"=>$themeid,":uniacid"=>$_G['mpid']);


    if($theme['status']==0){
        wxapp_result(1, '活动未开始');
        exit;
    }
    if($theme['status']==2){
        wxapp_result(1, '活动已结束');
        exit;
    }


    //员工信息处理---开始
    $isupdaterelation=false;
    $relation = Relation::getByThemeId($themeid,$_G['openid']);
    if(!empty($relation)){
        $fromuid = $relation['parentid'];
        $fopenid = $relation['popenid'];
        $workerid = $relation['workerid'];
    }

    $myworker = Worker::getThemeWorkerByOpenid($_G['openid'],$themeid,1);
    if (empty($myworker)){
        //如果来源为员工,则业绩给员工
        if (!empty($fromuid)){
            $theyworker = Worker::getThemeWorkerByUid($fromuid,$themeid,1);
            if (!empty($theyworker)){
                $fromuid = $theyworker['uid'];
                $fopenid = $theyworker['openid'];
                $workerid = $theyworker['uid'];
                $isupdaterelation=true;
            }
        }
        //如果来源为空,则给员工
        if (empty($fromuid) && !empty($workerid)){
            $theyworker = Worker::getThemeWorkerByUid($workerid,$themeid,1);
            $fromuid = $theyworker['uid'];
            $fopenid = $theyworker['openid'];
            $isupdaterelation=true;
        }
        //如果员工为空,则给来源所属员工
        if (!empty($fopenid) && empty($workerid)){
            $theyfrom = Relation::getByThemeId($themeid,$fopenid);
            $workerid = $theyfrom['workerid'];
            $isupdaterelation=true;
        }

        //在没有开启附近团的情况,当团员报名时,员工业绩归属与团长一致
        if ($config['isrecent']==0 && $recordid > 0 && $joinid == 1){
            $record = Record::getAttendGroupById($recordid);
            if (!empty($record['workerid'])){
                $workerid = $record['workerid'];
                $isupdaterelation=true;
            }
        }
        if ($isupdaterelation==true){
                Relation::update($relation['id'],array('parentid' => $fromuid,'popenid' => $fopenid,'workerid' => $workerid));
        }
    }elseif ($myworker['level']==4) {
        $superior = Worker::getThemeWorkerByUid($myworker['superior'],$themeid);
        $fromuid = $superior['uid'];
        $fopenid = $superior['openid'];
        $workerid = $_G['member']['uid'];
    }else{
        $fromuid = $_G['member']['uid'];
        $fopenid = $_G['openid'];
        $workerid = $_G['member']['uid'];
        if (empty($config['isworkerpay'])){
            if ($config['isxianxia']>0){
                $temptxt = "员工不可以报名,如需测试请用非员工微信,如需帮客户下单请用线下录入";
            }else{
                $temptxt = "员工不可以报名,如需测试请用非员工微信";
            }
            wxapp_result(1, $temptxt);
            exit;
        }


    }
//员工信息处理---结束


//录入信息--开始
    //如果底价下单或随时下单不需要录入信息
    if (empty($yukuan)) {
        $username = $_P['username'];
        $mobile   = $_P['mobile'];
        $option   = $_P['option'];
        $jiagetype   = $_P['jiagetype'];
        if ($system['gift']==1) {
           $giftidsvalue  = (array)$_P['address'];

           $giftids = serialize($giftidsvalue);
            $address = "";
            foreach ($giftidsvalue as $index => $id){
                
                $gift = db_find("SELECT * FROM ".tablename(t_gift)." WHERE id = ". $id);
                if (!empty($gift)){
                    if($index != 0){
                        $address.= "|";
                    }
                    $num = $index + 1 ;
                    $address.= $num .".". $gift['giftname'];
                }
            }

        }else{
           $address  = $_P['address'];
        }
        // $code     = $_P['code'];
        $datetime = $_P['datetime'];
        $addinfo = $_P['addinfo'];
        $formtwo = $_P['formtwo'];
    }else{
        //根据定单编号取信息
        $p3 = array(":recordid"=>$recordid,":themeid"=>$themeid);
        $recordinfo = db_find ( "SELECT * FROM " . tablename (t_record) . "
                                WHERE themeid =:themeid
                                        and id = :recordid order by id desc limit 1",$p3);
        $username = $recordinfo['username'];
        $mobile   = $recordinfo['mobile'];
        $option   = $recordinfo['option'];
        $address  = $recordinfo['address'];
        $datetime = $recordinfo['datetime'];
        $addinfo = $recordinfo['addinfo'];
        $formtwo = $recordinfo['formtwo'];
    }
    $username=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,，\-]#u','',$username);
    $mobile=preg_replace('#[^0-9]#u','',$mobile);
    $option=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_.,|，\-]#u','',$option);
    $address=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,，\-]#u','',$address);
    $datetime=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,，\-]#u','',$datetime);
    $addinfo=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,，\-]#u','',$addinfo);
    $formtwo=preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_,，\-]#u','',$formtwo);

    if ($joinid!=115){
        if(empty($username)){
            wxapp_result(1, '姓名为空');
            exit;
        }elseif(empty($mobile)){
            wxapp_result(1, '电话为空');
            exit;
        }elseif(mb_strlen($mobile,"utf-8")!=11){
            wxapp_result(1, '请输入11位手机号');
            exit;
        }
    }
//录入信息--结束


    // if(empty($system['appid']) || empty($system['mchid'] )){
    //     wxapp_result(1, '姓名为空');
    //     exit;
    // }
    $fee  = 0;
    $pid  = 0;
    $desclen=26;
    if (!empty($theme['mobile'])){
        $desc = "【客服".$theme['mobile']."】";
        $desclen = $desclen-mb_strlen($desc);
    }
    if (!empty($theme['jubf']) ){
        $desc = mb_substr($theme['jubf'],0,$desclen,"UTF-8").$desc;
    }else{
        $desc = mb_substr($theme['title'],0,$desclen,"UTF-8").$desc;
    }


    $type = $joinid;

//    $myrecord = db_find ( "SELECT * FROM " . tablename (t_record) . "
//                            WHERE uniacid = :uniacid and themeid =:themeid
//                                    and openid = :openid and type = 0 and status > 0 order by id desc limit 1",$p);

    //补余款
//    if ($config['yukuan']>0 && TIMESTAMP>$config['yukuantime']){
//        if (empty($yukuan)) {
//            $fee = $config['yukuan'];
//        }else{
//            $orderpay = db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
//                WHERE themeid = '{$themeid}' and paystate = 1 and realfee > 0 and uid='{$_G['member']['uid']}'" );
//            $fee = sprintf("%.2f",$config['yukuan'] - $orderpay);
//            $type = 8;
//        }
//    }


//支付金额处理--开始

// 20发起砍价
// 21随时下单
// 22底价下单
// 23原价购买-单买
    if ($joinid==20){
        if ($config['bargain_mode']==0 || $config['bargain_mode']==1){
            if ($config['bargain_joinprice']=='0.00'){
                $fee=$config['bargain_minprice'];
            }else{
                $fee=$config['bargain_joinprice'];
            }
        }else{
            $fee=0;
        }
    }elseif ($joinid==23){
        $fee=$config['bargain_marketprice'];
    }elseif ($joinid==24){
        $fee=$config['bargain_buy'];
    }else {
        //如果没有设置定金则支付当前价格
        if ($config['bargain_joinprice']=='0.00'){
            $result= Bargain::getUserLastBargainEntry($themeid,$_G['member']['uid'],$recordid);;
            $fee = $result['remain_amount'];
        }else{
            $fee=$config['bargain_joinprice'];
        }
    }

//支付金额处理--结束

    $uncode = $themeid.'-'.TIMESTAMP.rand(1000,1000000);
    if($theme['iskj']==1){

    }else{
        $uncode = $themeid.'-'.TIMESTAMP.rand(1000,1000000);
    }

    //load_model('mc');
    member_update($_G['member']['uid'],array('mobile' => $mobile,'realname'=>$username));

    //自动更新档案信息
    $data = array(
        'username' => $username,
        'mobile'   => $mobile,
        'addtime'  => TIMESTAMP,
        'address'  => $address,
        'datetime' => $datetime,
        'addinfo' => $addinfo,
        'formtwo' => $formtwo,
        'option' => option,
        'jiagetype'   => $jiagetype,
        'fromuid'  => $fromuid,
        'fopenid'  => $fopenid,
        'workerid'  => $workerid,
    );
    if ($config['isduoxuan']!=1 || $joinid ==115){
        $data['option'] = $option;
    }

    if ($system['hdget']==1) {
        if (Fans::getuid_old($fromuid,$themeid)) {
            $data['fromuid_old']  = $fromuid;
            $data['fopenid_old']  = $fopenid;
        }
        if (Fans::getuid_old($workerid,$themeid)) {
            $data['workerid_old']  = $workerid;
        }
    }

    $r = db_update(t_fans,$data,array("uid"=>$_G['member']['uid']));


    $data = array(
        'uniacid'  => $_G['mpid'],
        'themeid'  => $themeid,
        'openid'   => $_G['openid'],
        'uid'      => $_G['member']['uid'],
        'nickname' => $fans['nickname'],
        'avatar'   => empty($fans['avatar']) ? $fans['headimgurl']:$fans['avatar'],
        'username' => $username,
        'mobile'   => $mobile,
        'addtime'  => TIMESTAMP,
        'fee'      => $fee,
        'address'  => $address,
        'giftids'  => $giftids,        
        'datetime' => $datetime,
        'addinfo' => $addinfo,
        'formtwo' => $formtwo,
        'option' => $option,
        'jiagetype'   => $jiagetype,
        // 'code'     => $code,
        'uncode'   => $uncode,
        'status'   => 0,
        'fromuid'  => $fromuid,
        'fopenid'  => $fopenid,
        'workerid'  => $workerid,
        'pid'      => $pid,
        'type'     => $type,
        'renshu'     => $renshu,
        'products_id'  => $_P['products_id'],
    );
    if ($config['isduoxuan']!=1 || $joinid ==115){
        $data['option'] = $option;

    }
    
    if ($system['hdget']==1) {
        if (Fans::getuid_old($fromuid,$themeid)) {
            $data['fromuid_old']  = $fromuid;
            $data['fopenid_old']  = $fopenid;
        }
        if (Fans::getuid_old($workerid,$themeid)) {
            $data['workerid_old']  = $workerid;
        }
    }

    $p3 = array(":uniacid"=>$_G['mpid'],":recordid"=>$recordid,":themeid"=>$themeid);
    $record = db_find ( "SELECT * FROM " . tablename (t_record) . "
                                    WHERE uniacid = :uniacid and themeid =:themeid
                                            and id=:recordid and status = 0 order by id desc limit 1",$p3);
        
    $billcode = '';
    
    
    if(empty($record)){
        $data['billcode'] = getMillisecond();
        $billcode = $data['billcode'];
        $r = $insertid = db_insert(t_record,$data);
        if(!empty($r)){
            $recordid = $insertid;
        }else{
            wxapp_result(1, '请重新下单');
            exit;
        }
        
        if($system['iswqpay']==1){
            // $result['errcode'] = 0;
            // $result['msg'] = 'success';
            // $result['url'] =   Theme::createwxAppUrl('dopay',array('recordid'=>$recordid));
            // return_msg($result, '', 'ajax');

            wxapp_result(1, '开启开系统支付');
            exit;
        }
        
    }else{
        $billcode = $record['billcode'];
        if($record['status'] == 0){
            $r = db_update(t_record,$data,array("id"=>$record['id']));
            if(!empty($r)){
                $recordid = $record['id'];
            }else{
                wxapp_result(1, '请重新下单');
                exit;
            }
            if($system['iswqpay']==1){
                wxapp_result(1, '系统开启系统支付');
                exit;
            }
        }elseif($record['status'] == 1){
            wxapp_result(1, '您已经报名了');
            exit;
        }elseif($record['status'] == 2){
            wxapp_result(1, '您已经核销过');
            exit;
        }else{
            wxapp_result(1, '请联系管理员');
            exit;
        }
    }
    //如果是后付款，则跳过支付
    if ($config['bargain_mode']>=2 && $joinid==20 || $fee==0){
        //调用砍价实例
        $r = Bargain::apiCreateBargain($theme,$config,$themeid,$_G['member']['uid'],$recordid,$system);

        wxapp_result($r['errcode'], $r['msg'],['recordid'=>$recordid]);
        exit;
    }

    $p[':recordid'] = $recordid;
    $order = db_find ( "SELECT * FROM ".tablename(t_order)."
            WHERE uniacid = :uniacid and themeid = :themeid and openid = :openid and orderfee>0 and masterid=:recordid",$p);
    $data = array(
            'uniacid'  => $_G['mpid'],
            'ordertype'=> $type,
            'themeid'  => $themeid,
            'openid'   => $_G['openid'],
            'uid'       => $_G['member']['uid'],
            'username' => $username,
            'mobile'   => $mobile,
            'status'   => 0,
            'type'     => 'wechat',
    );
    $data['orderfee'] = $fee;
    $data['masterid'] = $recordid;
    $data['detailid'] = $recordid;
    $orderid = 0;
    $tid = '';
    if(empty($order)){
        $module_item = db_get('yx_sys_modules', ['module_name' => MODULE_NAME, 'themeid' => $themeid]);
        $module_id = empty($module_item['id']) ? '000000' : sprintf("%06d", $module_item['id']);
        $uniontid = date('YmdHis') . $module_id . random(8, 1);
        $billcode = getMillisecond();
        $tid = '0'.$billcode;
        $data['tid'] = $tid;
        $data['addtime'] = TIMESTAMP;
        $data['ordersn'] = $billcode;
        $orderid = Order::save($data);
    }elseif($order['paystate'] == 0){
        // $tid = $order['tid'];
        // $orderid = $order['id'];
        $data['addtime'] = TIMESTAMP;
        if(TIMESTAMP - $order['addtime'] > 300 || $order['orderfee'] != $fee){
            $ordersn = getMillisecond();
            $data['ordersn'] = $ordersn;
            $tid = '2'.$ordersn;
            $data['tid'] = $tid;
            //确保定单号不重复
            $sql = "SELECT * FROM " . tablename(t_order) . " WHERE ordersn ='" .$data['ordersn'] . "'";
            $row = db_find($sql);
            if (!empty($row)) {
                $data['ordersn'] = getMillisecond();
                $tid = '2'.$data['ordersn'];
                $data['tid'] = $tid;
                $sql = "SELECT * FROM " . tablename(t_order) . " WHERE ordersn ='" .$data['ordersn'] . "'";
                $row = db_find($sql);
                if (!empty($row)) {
                    $data['ordersn'] = getMillisecond();
                    $tid = '2'.$data['ordersn'];
                    $data['tid'] = $tid;
                }
            }
        }
        Order::update($order['id'],$data);
        $orderid = $order['id'];
    }elseif($order['paystate'] == 1){
        wxapp_result(1, '请联系管理员');
        exit;
    }else{
        wxapp_result(1, '请联系管理员');
        exit;
    }
    // $result=  array();
    // $result['errcode'] = 0;
    // // $result['orderid'] =  $orderid;
    // $result['tid'] =  $tid;
    // $result['fee'] =  $fee;
    // $result['title'] =  $desc;
    // $result['payway'] = 0;
    // $result['url'] =   Theme::createwxAppUrl('dopay',array('orderid'=>$orderid));
    // return_msg($result, '', 'ajax');


    $params = array('isrecharge'=>false);
    $ordertype = 'theme';

    if(empty($_G['openid']) || empty($_G['member']['uid'])){
        wxapp_result(1, '用户信息错误');
        return;
    }
    // $orderid = intval($_P['orderid']);
    $order = Order::getByIdAndOpenid($orderid,$_G['openid']);
    if(empty($order)){
        wxapp_result(1, '记录不存在，请重新下单');
        exit;
    }
    if($order['status'] != 0){
        wxapp_result(1, '定单已完成支付');
        exit;
    }
    if($order['orderfee'] <= 0){
        wxapp_result(1, '定单金额必须大于0元');
        exit;
    }

    
    $desclen=26;        
    $theme = Theme::getThemeById($order['themeid']);
    if (!empty($theme['mobile'])){
        $desc = "【客服".$theme['mobile']."】";
        $desclen = $desclen-mb_strlen($desc);
    }
    if (!empty($theme['jubf']) ){
        $desc = mb_substr($theme['jubf'],0,$desclen,"UTF-8").$desc;
    }else{
        $desc = mb_substr($theme['title'],0,$desclen,"UTF-8").$desc;
    }
    $title = $desc;

    $params ['themeid'] = $order['themeid'];
        $params ['uniontid'] = $order['uniontid'];
        $params ['tid'] = $order['tid'];
    $params ['user'] = $_G['openid'];
    $params ['fee'] =  $order['orderfee'];
    $params ['title'] = $title;
    $params ['ordersn'] = $order['ordersn'];
    $params ['virtual'] = false;
    
    $pay_params = $this->pay ( $params );
    // $data['params']=$pay_params ;
    if (is_error($pay_params)) {
        return wxapp_result(1, '支付失败：'.$pay_params['message'],$pay_params);
    }
    return wxapp_result(0, '', $pay_params);
}
}